const express = require('express');
const router = express.Router();
const database = require('../utils/database');

/**
 * 用户端路由
 * 处理用户端的API请求
 */

/**
 * 获取所有区域列表
 * GET /api/areas
 */
router.get('/areas', async (req, res) => {
    try {
        console.log('获取区域列表请求');
        const areas = await database.all('SELECT * FROM areas ORDER BY name');
        res.json({
            success: true,
            data: areas
        });
    } catch (error) {
        console.error('获取区域列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取区域列表失败',
            error: error.message
        });
    }
});

/**
 * 根据区域ID获取维修项目列表
 * GET /api/items/:areaId
 */
router.get('/items/:areaId', async (req, res) => {
    try {
        const { areaId } = req.params;
        console.log(`获取区域${areaId}的维修项目列表`);
        
        const items = await database.all(
            'SELECT * FROM repair_items WHERE area_id = ? ORDER BY name',
            [areaId]
        );
        
        res.json({
            success: true,
            data: items
        });
    } catch (error) {
        console.error('获取维修项目列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取维修项目列表失败',
            error: error.message
        });
    }
});

/**
 * 提交计价单
 * POST /api/quotations
 */
router.post('/quotations', async (req, res) => {
    try {
        const { area_id, location, person, repair_date, items, total_price } = req.body;
        
        console.log('提交计价单:', { area_id, location, person, repair_date, total_price });
        
        // 验证必填字段
        if (!area_id || !location || !person || !repair_date || !items || !total_price) {
            return res.status(400).json({
                success: false,
                message: '请填写所有必填字段'
            });
        }
        
        // 验证items格式
        let itemsJson;
        try {
            itemsJson = typeof items === 'string' ? items : JSON.stringify(items);
            JSON.parse(itemsJson); // 验证JSON格式
        } catch (e) {
            return res.status(400).json({
                success: false,
                message: '维修项目数据格式错误'
            });
        }
        
        // 插入计价单
        const result = await database.run(
            `INSERT INTO quotations (area_id, location, person, repair_date, items, total_price) 
             VALUES (?, ?, ?, ?, ?, ?)`,
            [area_id, location, person, repair_date, itemsJson, total_price]
        );
        
        console.log('计价单提交成功，ID:', result.id);
        
        res.json({
            success: true,
            message: '计价单提交成功',
            data: { id: result.id }
        });
    } catch (error) {
        console.error('提交计价单失败:', error);
        res.status(500).json({
            success: false,
            message: '提交计价单失败',
            error: error.message
        });
    }
});

/**
 * 获取计价单详情
 * GET /api/quotations/:id
 */
router.get('/quotations/:id', async (req, res) => {
    try {
        const { id } = req.params;
        console.log(`获取计价单详情，ID: ${id}`);
        
        const quotation = await database.get(
            `SELECT q.*, a.name as area_name 
             FROM quotations q 
             LEFT JOIN areas a ON q.area_id = a.id 
             WHERE q.id = ?`,
            [id]
        );
        
        if (!quotation) {
            return res.status(404).json({
                success: false,
                message: '计价单不存在'
            });
        }
        
        // 解析items JSON
        try {
            quotation.items = JSON.parse(quotation.items);
        } catch (e) {
            console.warn('解析计价单项目JSON失败:', e);
        }
        
        res.json({
            success: true,
            data: quotation
        });
    } catch (error) {
        console.error('获取计价单详情失败:', error);
        res.status(500).json({
            success: false,
            message: '获取计价单详情失败',
            error: error.message
        });
    }
});

module.exports = router;